import Taro from '@tarojs/taro'
const { rpc, fromNowOn } = require('../../utils/util.js')
const service = require('./service.js')
const regeneratorRuntime = require('../../utils/async.js')
const app = (module.exports = {})
const App = Taro.getApp()

app.loadMore = async (params, action, state) => {
  const { articles } = state
  const { key } = params

  if (!articles[key].showLoading) {
    articles[key].showLoading = true
    await action.setData({ articles })
    await action.dispatch('getList', params)
  }
}
app.getList = async (params, action, state) => {
  const { key = '我的', pageIndex = 1, pageSize = 10 } = params
  const { articles } = state
  const dataMap = result => result;
  // const suggested = Taro.getStorageSync('artcleSuggested');
  const art = await rpc(
    service.getArticle, 
    { 
      page: pageIndex, 
      per_page: pageSize
    }, 
    { dataMap }
  );
  const artList = art.data
  const total = artList.meta.number_of_update || 0

  articles[key] = articles[key] || {}
  articles[key].pageIndex = pageIndex
  articles[key].updateNum = total
  articles[key].showLoading = false
  articles[key].hasMore = pageSize * pageIndex < total
  articles[key].articles = [ ...(articles[key].articles || []), ...artList.articles ]

  await action.setData({ articles })
  return articles
}

app.getMe = async (params, action, state) => {
  const me = await rpc(service.getMe, {})
  await action.setData({ me })
}
